package com.nuatar.meibi.pubvar;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;

import com.nuatar.meibi.tool.PowerTool;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class PhoneMaster {

	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}

	public static String getFileMd5(File f, int seek, int length) {
		String result = "";
		try {
			result = getMd5(getFileByteArray(f, seek, length));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] getFileByteArray(File f, int seek, int length)
			throws FileNotFoundException, IOException {
		DataInputStream dis = new DataInputStream(new FileInputStream(f));
		byte[] b1 = new byte[length];
		dis.skip(seek);
		dis.read(b1);
		dis.close();
		return b1;
	}

	public static String getMd5(byte[] a) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(a);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}

		return md5StrBuff.toString();
	}

	public static ImagePair[] getImagePairs(String a) {
		String[] pp = a.split(",");
		ImagePair ip[] = new ImagePair[pp.length];
		for (int j = 0; j < pp.length; j++) {
			ip[j] = new ImagePair();
			ip[j].Length = Integer.parseInt(pp[j].split("&")[0]);
			ip[j].Md5 = pp[j].split("&")[1];
			if (j == 0) {
				ip[j].Seeker = 0;
			} else {
				ip[j].Seeker = ip[j - 1].Seeker + ip[j - 1].Length;
			}
		}
		return ip;
	}

	public static WallPaper setWallPaperImagePairs(WallPaper wp) {
		WallPaper temp = new WallPaper();
		temp.id = wp.id;
		temp.title = wp.title;
		temp.creatDate = wp.creatDate;
		temp.viewc = wp.viewc;
		String path = getFilePathFromId(wp.id, ".des");
		String data[] = getDesFileString(path);
		temp.ShortImages = getImagePairs(data[0]);
		temp.BigImages = getImagePairs(data[1]);
		return temp;
	}

	public static ImagePair getFirstImagePair(String id) {
		String path = getFilePathFromId(id, ".des");
		String data[] = getDesFileString(path);
		if (getImagePairs(data[0]) != null
				&& getImagePairs(data[0]).length >= 1) {
			return getImagePairs(data[0])[0];
		} else {
			return null;
		}
	}

	public static String[] getDesFileString(String path) {
		File f = new File(path);
		String[] result = new String[2];
		byte[] bs = new byte[(int) f.length()];
		DataInputStream dis;
		try {
			dis = new DataInputStream(new FileInputStream(f));
			dis.read(bs, 0, bs.length);
			String all = new String(bs, "UTF-8");
			result[0] = all.split("#")[0];
			result[1] = all.split("#")[1];
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;

	}

	public static String getFilePathFromId(String id, String ext) {
		return Environment.getExternalStorageDirectory().getPath()
				+ Configer.DirHead + id + "/" + id + ext;
	}

	public static String getURLFromId(String id, String ext) {
		return Configer.BaseServer
				+ Configer.Bucket
				+ "/"
				+ id
				+ ext
				+ "?sign=MBO:EBc9d7def393abe588e063fdd7db30ca:"
				+ PowerTool
						.getKey(Configer.Bucket, "GET", "/" + id + ext, null);
	}

	public static Bitmap getBitmapFromBdt(String id, ImagePair ip) {
		Bitmap bmp = null;
		String path = getFilePathFromId(id, ".bdt");
		File f = new File(path);
		byte[] bs;
		try {
			bs = PhoneMaster.getFileByteArray(f, ip.Seeker, ip.Length);
			InputStream is = new ByteArrayInputStream(bs);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			bmp = BitmapFactory.decodeStream(is, null, options);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bmp;

	}

	public static boolean VerifyImage(String savePath, ImagePair ip) {
		boolean result = false;
		File f = new File(savePath);
		if (f.exists()) {
			String LocalMD5;
			String Ipmd5 = ip.Md5;
			LocalMD5 = getFileMd5(f, ip.Seeker, ip.Length);
			if (LocalMD5.equals(Ipmd5)) {
				result = true;
			} else {
				result = false;
			}

		} else {
			result = false;
		}
		return result;
	}

	public static boolean DateCmp(Date workDay, Date currTime) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(workDay);
		c2.setTime(currTime);
		if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
				&& (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH))
				&& c1.get(Calendar.DAY_OF_MONTH) == c2
						.get(Calendar.DAY_OF_MONTH)) {
			return true;
		} else {
			return false;
		}
	}
}
